package com.yiquan.comment.interceptor;

import com.alibaba.fastjson.JSON;
import entity.Result;
import entity.StatusCode;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import util.JwtUtil;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class MyInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private JwtUtil jwtUtil;
//
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            return true;
        }
        //获取userId
        String authHeader = request.getHeader("Authorization");
        if (authHeader != null && authHeader.startsWith("yiquan-")) {
            String token = authHeader.substring(7);
            Claims claims = jwtUtil.parseJWT(token);
            if (claims == null || claims.getId() == null || claims.getId().equals("")){
                return responseInvalidateRequest(response,new Result(false, StatusCode.NEED_LOGIN_IN,"token非法或过期"));
            }else {
                log.info("获取token,userId:{}",claims.getId());
                request.setAttribute("user_id",claims.getId());
                return true;
            }
            // request.setAttribute("userId",userId);
        }
        return responseInvalidateRequest(response,new Result(false, StatusCode.NEED_LOGIN_IN,"请登陆后再进行相关操作"));
    }

    /**
     * 输出非法请求的响应
     * @param response
     * @param result
     * @return
     * @throws Exception
     */
    private boolean responseInvalidateRequest(HttpServletResponse response, Result result ) throws Exception{
        response.setContentType("application/json;;charset=UTF-8");
        response.getWriter().write(JSON.toJSONString(result));
        return false;
    }
}
